package com.cci.kangdao.cipFleet.service.impl;

import com.alibaba.fastjson.JSON;
import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.cipFleet.dto.request.CipFleetAndEsnRequest;
import com.cci.kangdao.cipFleet.dto.request.CipFleetDelRequest;
import com.cci.kangdao.cipFleet.dto.request.CipFleetRequest;
import com.cci.kangdao.cipFleet.dto.request.CipFleetUpdateRequest;
import com.cci.kangdao.cipFleet.dto.response.CipEntityResponse;
import com.cci.kangdao.cipFleet.dto.response.CipFleetResponse;
import com.cci.kangdao.cipFleet.dto.response.CipSuccessResponse;
import com.cci.kangdao.cipFleet.dto.response.CipVehicleResponse;
import com.cci.kangdao.cipFleet.entity.CipFleetT;
import com.cci.kangdao.cipFleet.entity.CipVehicleT;
import com.cci.kangdao.cipFleet.entity.ExternalCustomerESNT;
import com.cci.kangdao.cipFleet.service.CipFleetService;
import com.cci.kangdao.cipapi.CipServiceApi;
import com.cci.kangdao.controller.shankang.service.ShanKangSycMedbFleetService;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.ServiceAgreement;
import com.cci.kangdao.dao.model.UserChannelT;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dto.BaseResponse;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service("CipFleetService")
public class CipFleetServiceImpl implements CipFleetService {

	private Logger log = Logger.getLogger(this.getClass().getName());

	@Resource
	private CipFleetMapper cipFleetMapper;
	@Resource
	private CipVehicleMapper cipVehicleMapper;
	@Resource
	private EngineMsgDao engineMsgDao;
	@Resource
	private CustomerEngineRelTDao customerEngineRelTDao;
	@Resource
	private ServiceAgrementDao serviceAgrementDao;

	@Resource
	private ExternalCustomerESNTMapper externalCustomerESNTMapper;
	@Resource
	private CipServiceApi cipServiceApi;
	@Resource
	private UserChannelTMapper userChannelTMapper;
	@Resource
	private UserTDao userTDao;
	@Resource
	private ShanKangSycMedbFleetService shanKangSycMedbFleetService;

	/**
	 * 获取车队信息
	 *
	 * @param userId
	 * @return
	 */
	@Override
	public List<CipFleetResponse> getFleetByUserId(Long userId, Integer type) {
		//是否白名单
		//int i = cipFleetMapper.isFleetWhite(userId);
		//if(i > 0){
		//获取车队信息
		List<CipFleetResponse> list = new ArrayList<>();
		List<CipFleetResponse> fleetList = cipFleetMapper.getFleetByUserId(userId, type);
		if (CollectionUtils.isNotEmpty(fleetList)) {
			List<Long> idList = fleetList.stream().map(CipFleetResponse::getId).filter(a -> null != a).collect(Collectors.toList());
			if (type == 1) {
				//获取车辆信息
				List<CipVehicleResponse> vehicleList = cipFleetMapper.getVehicleByList(userId, idList);
				if (CollectionUtils.isNotEmpty(vehicleList)) {
					for (CipFleetResponse fleet : fleetList) {
						List<CipVehicleResponse> clist = new ArrayList<>();
						for (CipVehicleResponse vehicle : vehicleList) {
							if (fleet.getId().equals(vehicle.getFleetId())) {
								clist.add(vehicle);
							}
						}
						fleet.setVehicleInfos(clist);
					}
				}
				list.addAll(fleetList);
			} else {
				//获取车辆信息
				List<CipVehicleResponse> vehicleList = cipFleetMapper.getVehicleByListExternal(userId, idList, type);
				if (CollectionUtils.isNotEmpty(vehicleList)) {
					for (CipFleetResponse fleet : fleetList) {
						List<CipVehicleResponse> clist = new ArrayList<>();
						for (CipVehicleResponse vehicle : vehicleList) {
							if (fleet.getId().equals(vehicle.getFleetId())) {
								clist.add(vehicle);
							}
						}
						fleet.setVehicleInfos(clist);
					}
				}
				list.addAll(fleetList);
			}

		}
		CipFleetResponse noFleet = new CipFleetResponse();
		noFleet.setId(-1L);
		//无车队车辆
		List<CipVehicleResponse> vehicleList = cipFleetMapper.getNoFleetByList(userId);
		noFleet.setVehicleInfos(vehicleList);
		list.add(noFleet);
		return list;
		//}
		//return null;
	}

	/**
	 * 是否白名单
	 * @return
	 */
	@Override
	public boolean isFleetWhite(Long userId) {
		int i = cipFleetMapper.isFleetWhite(userId);
		return i > 0;
	}

	/**
	 * 添加车队信息
	 * @param fleetList
	 * @return
	 */
	@Override
	public boolean insertFleet(List<CipFleetRequest> fleetList) {
		for(CipFleetRequest fleet : fleetList){
			Long fleetId = null;
			if(StringUtils.isNotBlank(fleet.getFleetCode())){
				fleetId = cipFleetMapper.fleetCheck(fleet.getUserId(),fleet.getFleetCode());
			}
			CipFleetT cipFleetT = new CipFleetT();
			if(null != fleetId){
				cipFleetT.setId(fleetId);
				cipFleetT.setFleetType(fleet.getFleetType());
				cipFleetT.setFleetName(fleet.getFleetName());
				cipFleetT.setUpdator(fleet.getUserId());
				cipFleetT.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
				cipFleetMapper.updateFleet(cipFleetT);
			} else {
				cipFleetT.setUserId(fleet.getUserId());
				cipFleetT.setFleetName(fleet.getFleetName());
				cipFleetT.setFleetType(fleet.getFleetType());
				cipFleetT.setFlag(0);
				cipFleetT.setCreator(fleet.getUserId());
				cipFleetT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
				int count = cipFleetMapper.getFleetCount();
				cipFleetT.setFleetCode("Fl" + count);
				cipFleetMapper.insertFleet(cipFleetT);
			}
			this.insertVehicleList(fleet.getVehicleInfos(),fleet.getUserId(),cipFleetT.getId());
		}
		return true;
	}

	/**
	 * 添加车辆信息
	 * @param vehicleInfoList
	 * @return
	 */
	@Override
	public boolean insertVehicleList(List<CipVehicleResponse> vehicleInfoList,Long userId,Long fleetId) {
		String time = LocalTimeUtil.getRealCurrentTime();
		int count = cipFleetMapper.deleteVehicle(fleetId,userId,time);
		if(CollectionUtils.isNotEmpty(vehicleInfoList) && null != userId && null != fleetId){
			for(CipVehicleResponse vehicle : vehicleInfoList){
				//用户车辆信息
				CipVehicleT userESN = cipFleetMapper.getUserESN(userId,vehicle.getEsn());
				//校验一个车队下是否有这辆车
				Long vehicleId = cipFleetMapper.vehicleCheck(fleetId,vehicle.getEsn());
				if(null != userESN && null == vehicleId){
					CipVehicleT cipVehicleT = new CipVehicleT();
					cipVehicleT.setEsn(vehicle.getEsn());
					cipVehicleT.setPlateNumber(StringUtils.isNotBlank(vehicle.getPlateNumber()) ? vehicle.getPlateNumber() : userESN.getPlateNumber());
					cipVehicleT.setFleetId(fleetId);
					cipVehicleT.setUserId(userId);
					cipVehicleT.setFlag(0);
					cipVehicleT.setCreator(userId);
					cipVehicleT.setCreateTime(time);
					cipFleetMapper.insertVehicle(cipVehicleT);
				}
			}
		}
		return true;
	}

	/**
	 * 删除车队信息
	 * @param fleetList
	 * @return
	 */
	@Override
	public boolean deleteFleet(List<CipFleetDelRequest> fleetList) {
		String time = LocalTimeUtil.getRealCurrentTime();
		for(CipFleetDelRequest fleet : fleetList) {
			Long fleetId = cipFleetMapper.fleetCheck(fleet.getUserId(), fleet.getFleetCode());
			cipFleetMapper.deleteFleet(fleetId,fleet.getUserId(),time);
			cipFleetMapper.deleteVehicle(fleetId,fleet.getUserId(),time);
		}
		return true;
	}


	/**
	 * 根据当前登录用户获取车队信息
	 *
	 * @return
	 */
	@Override
	public BaseResponse appGetFleetList(Long userId, String externalUserId, Integer type) {
		//获取当前用户
		if(null == userId && StringUtils.isNotBlank(externalUserId)){
			Long channelUserId = userChannelTMapper.getUserChannelByExternalUserIdAndChannel(externalUserId,String.valueOf(type));
			if(null != channelUserId){
				userId = channelUserId;
			}
		}
		log.info("获取车队信息:userId:" + userId + ";externalUserId:" + externalUserId+ ";type:" + type);
		//获取当前用户绑定的所有车队
		List<Map<String, Object>> fleetMapList = cipFleetMapper.getFleetListByUserId(userId, externalUserId, type);
		if (CollectionUtils.isNotEmpty(fleetMapList)) {
			Long finalUserId = userId;
			Integer finalType = type;
			String finalExternalUserId = externalUserId;
			fleetMapList.stream().forEach(fleetMap -> {
				if (null != finalUserId) {
					List<Map<String, Object>> fleetEsnList = cipVehicleMapper.getFleetEsnList(MapUtils.getLongValue(fleetMap, "fleetId"), finalUserId, finalExternalUserId, finalType);
					fleetMap.put("esnList", CollectionUtils.isNotEmpty(fleetEsnList) ? fleetEsnList : new ArrayList<>());
					fleetMap.put("fleetEsnNum", CollectionUtils.isNotEmpty(fleetEsnList) ? fleetEsnList.size() : 0);
				} else {
					List<Map<String, Object>> fleetEsnList = cipVehicleMapper.getExternalFleetEsnList(MapUtils.getLongValue(fleetMap, "fleetId"), finalExternalUserId, finalType);
					fleetMap.put("esnList", CollectionUtils.isNotEmpty(fleetEsnList) ? fleetEsnList : new ArrayList<>());
					fleetMap.put("fleetEsnNum", CollectionUtils.isNotEmpty(fleetEsnList) ? fleetEsnList.size() : 0);
				}
				//遍历查询每个车队下所有绑定的esn信息

			});
		}
		return BaseResponse.success(fleetMapList);
	}


	//app新增车队接口
	@Transactional
	@Override
	public BaseResponse appAddFleet(CipFleetAndEsnRequest cipFleetAndEsnRequest){
		//获取当前用户
		UserT userT = UserThreadLocal.get();
		//数据校验
		if (StringUtils.isBlank(cipFleetAndEsnRequest.getFleetName()) || -1 == cipFleetAndEsnRequest.getFleetType()
				|| -1 == cipFleetAndEsnRequest.getApplicationType()) {
			return BaseResponse.error(17, "缺少必填参数！");
		}
		if (CollectionUtils.isNotEmpty(cipFleetAndEsnRequest.getEsnList())) {
			for (CipFleetAndEsnRequest.EsnRequest esnRequest : cipFleetAndEsnRequest.getEsnList()) {
				if (StringUtils.isEmpty(esnRequest.getEsn()) || StringUtils.isEmpty(esnRequest.getPlateNumber())) {
					return BaseResponse.error(17, "缺少必填参数！");
				}
			}
		}
		if (1 == cipFleetAndEsnRequest.getType()) {
			//验证是否签署了主动服务协议
			ServiceAgreement serviceAggrementDetail = serviceAgrementDao.getServiceAggrementDetail(userT.getId(), 0);
			if (Objects.isNull(serviceAggrementDetail)) {
				return BaseResponse.error(-99, "请签署主动服务协议！");
			}
		}
		//校验车队名称是否存在
		int isExist = this.checkFleetName(cipFleetAndEsnRequest.getFleetName(),cipFleetAndEsnRequest.getType(),null != userT ? userT.getId() : null,cipFleetAndEsnRequest.getExternalUserId());
		if(isExist > 0){
			return BaseResponse.error(-98, "车队名称已存在！");
		}
		String time = LocalTimeUtil.getRealCurrentTime();
		//1.插入车队表
		CipFleetT cipFleetT = new CipFleetT();
		cipFleetT.setFleetName(cipFleetAndEsnRequest.getFleetName());
		cipFleetT.setFleetType(cipFleetAndEsnRequest.getFleetType());
		cipFleetT.setApplicationType(cipFleetAndEsnRequest.getApplicationType());
		if (1 != cipFleetAndEsnRequest.getType()) {
			cipFleetT.setServiceChannel(String.valueOf(cipFleetAndEsnRequest.getType()));
			cipFleetT.setCreator(Long.valueOf(cipFleetAndEsnRequest.getType()));
			cipFleetT.setExternalUserId(cipFleetAndEsnRequest.getExternalUserId());
			cipFleetT.setUserId(userChannelTMapper.getUserChannelByExternalUserIdAndChannel(cipFleetAndEsnRequest.getExternalUserId(),String.valueOf(cipFleetAndEsnRequest.getType())));
		} else {
			cipFleetT.setCreator(userT.getId());
			cipFleetT.setUserId(userT.getId());
			cipFleetT.setServiceChannel("1");
		}
		cipFleetT.setType(cipFleetAndEsnRequest.getType());
		cipFleetT.setCreateTime(time);
		cipFleetT.setFleetCode("fl" + cipFleetMapper.getFleetCount());
		//添加车队同步cip
		cipFleetAndEsnRequest.setServiceChannel(cipFleetT.getServiceChannel());
		cipFleetAndEsnRequest.setExternalUserId(cipFleetT.getExternalUserId());
		cipFleetAndEsnRequest.setUserId(String.valueOf(cipFleetT.getUserId()));
		cipFleetAndEsnRequest.setFleetCode(cipFleetT.getFleetCode());
		CipSuccessResponse response = cipServiceApi.fleetAddCip(cipFleetAndEsnRequest);
        if(null != response && "0".equals(response.getStatus()) && null != response.getData() && StringUtils.isNotBlank(response.getData().getFleetId())){
			cipFleetT.setCipFleetId(response.getData().getFleetId());
		} else {
			String msg = null != response && StringUtils.isNotBlank(response.getMsg()) ? response.getMsg() : "同步cip失败";
			return BaseResponse.error(-99,msg);
		}
		int insertFleetNum = cipFleetMapper.insertFleet(cipFleetT);
		//2.车队和esn绑定关系
		List<CipFleetAndEsnRequest.EsnRequest> esnList = cipFleetAndEsnRequest.getEsnList();
		if (insertFleetNum > 0 && CollectionUtils.isNotEmpty(esnList)) {
			esnList.stream().forEach(esn -> {
				CipVehicleT cipVehicleT = new CipVehicleT();
				if (1 != cipFleetAndEsnRequest.getType()) {
					cipVehicleT.setCreator(Long.valueOf(cipFleetAndEsnRequest.getType()));
					cipVehicleT.setExternalUserId(cipFleetAndEsnRequest.getExternalUserId());
					cipVehicleT.setUserId(userChannelTMapper.getUserChannelByExternalUserIdAndChannel(cipFleetAndEsnRequest.getExternalUserId(),String.valueOf(cipFleetAndEsnRequest.getType())));
				} else {
					cipVehicleT.setCreator(userT.getId());
					cipVehicleT.setUserId(userT.getId());
				}
				cipVehicleT.setFleetId(cipFleetT.getId());
				cipVehicleT.setEsn(esn.getEsn());
				cipVehicleT.setPlateNumber(esn.getPlateNumber());

				cipVehicleT.setCreateTime(time);
				cipFleetMapper.insertVehicle(cipVehicleT);
				if (1 == cipFleetAndEsnRequest.getType()) {
					//3.更新发动机基础数据表里对esnPowerType应esn的应用类型和动力类型字段
					Map<String, Object> esnMap = new HashMap<>();
					esnMap.put("esnPowerType", cipFleetT.getFleetType());
					esnMap.put("esnApplicationType", cipFleetT.getApplicationType());
					esnMap.put("ESN", esn.getEsn());
					engineMsgDao.updateMsgByEsn(esnMap);
				}
			});
		}
		//陕康云  同步的车队至 medb
		if(cipFleetAndEsnRequest.getType()==4){
			log.error("111111"+JSON.toJSONString(cipFleetAndEsnRequest));
			Long userChannelByExternalUserIdAndChannel = userChannelTMapper.getUserChannelByExternalUserIdAndChannel(cipFleetAndEsnRequest.getExternalUserId(), String.valueOf(cipFleetAndEsnRequest.getType()));
			log.error("222222:" + userChannelByExternalUserIdAndChannel);
			UserT userTSelect = userTDao.selectById(userChannelByExternalUserIdAndChannel);
			if (null != userTSelect) {
				if (StringUtils.isNotBlank(userTSelect.getShankangWWID())) {
					List<String> esnStrList = new ArrayList<>();
					if(CollectionUtils.isNotEmpty(esnList)) {
						esnStrList  = esnList.stream().map(esn -> esn.getEsn()).collect(Collectors.toList());
					}
					Long medbFleetId = shanKangSycMedbFleetService.sycAddMedbFleet(cipFleetT, userTSelect, esnStrList);
					if (null !=medbFleetId) {
						CipFleetT fleetTUpdate = new CipFleetT();
						fleetTUpdate.setId(cipFleetT.getId());
						fleetTUpdate.setExternalFleetId(medbFleetId);
						cipFleetMapper.updateFleet(fleetTUpdate);
					}
				}
			}
		}
		Map<String,Object> returnMap = new HashMap<>();
		returnMap.put("fleetId", cipFleetT.getCipFleetId());
		return BaseResponse.success(returnMap);
	}


	//根据当前登陆人id校验车队名称是否存在
	@Override
	public int checkFleetName(String fleetName, Integer type, Long userId, String externalUserId) {
		log.info("校验车队名称是否存在信息:userId:" + userId + ";externalUserId:" + externalUserId+ ";type:" + type);
		if(null == userId && StringUtils.isNotBlank(externalUserId)){
			Long channelUserId = userChannelTMapper.getUserChannelByExternalUserIdAndChannel(externalUserId,String.valueOf(type));
			if(null != channelUserId){
				userId = channelUserId;
			}
		}
		return cipFleetMapper.fleetNameCheck(userId, externalUserId, fleetName, type) > 0 ? 1 : 0;
	}


	//获取设备列表
	@Override
	public BaseResponse appGetEquipmentList(Long userId, String externalUserId, Integer type) {
		log.info("获取设备列表:userId:" + userId + ";externalUserId:" + externalUserId+ ";type:" + type);
		if(null == userId && StringUtils.isNotBlank(externalUserId)){
			Long channelUserId = userChannelTMapper.getUserChannelByExternalUserIdAndChannel(externalUserId,String.valueOf(type));
			if(null != channelUserId){
				userId = channelUserId;
			}
		}
		if (null != userId) {
			List<Map<String, Object>> equipmentList = customerEngineRelTDao.getEquipmentListByUserId(userId);
			return BaseResponse.success(equipmentList);
		} else {
			List<ExternalCustomerESNT> list = new ArrayList<>();
			if (null != externalUserId) {
				list = externalCustomerESNTMapper.selectByUserId(externalUserId, type);
			}
			return BaseResponse.success(list);
		}

	}


	//app修改车队接口
	@Transactional
	@Override
	public BaseResponse appUpdateFleet(CipFleetAndEsnRequest cipFleetAndEsnRequest){
		Integer type = cipFleetAndEsnRequest.getType();
		//获取当前用户
		UserT userT = UserThreadLocal.get();
		//数据校验
		if (StringUtils.isEmpty(cipFleetAndEsnRequest.getFleetName()) || -1 == cipFleetAndEsnRequest.getFleetType()
				|| -1 == cipFleetAndEsnRequest.getApplicationType() || (-1 == cipFleetAndEsnRequest.getFleetId() && StringUtils.isBlank(cipFleetAndEsnRequest.getCipFleetId()))) {
			return BaseResponse.error(17, "缺少必填参数！");
		}
		if (CollectionUtils.isNotEmpty(cipFleetAndEsnRequest.getEsnList())) {
			for (CipFleetAndEsnRequest.EsnRequest esnRequest : cipFleetAndEsnRequest.getEsnList()) {
				if (StringUtils.isEmpty(esnRequest.getEsn()) || StringUtils.isEmpty(esnRequest.getPlateNumber())) {
					return BaseResponse.error(17, "缺少必填参数！");
				}
			}
		}
		CipFleetT updateFleetT = cipFleetMapper.getFleetById(cipFleetAndEsnRequest.getFleetId(),cipFleetAndEsnRequest.getCipFleetId());
		if(null == updateFleetT){
			return BaseResponse.error(17, "未查询到车队数据！");
		}
		if(!cipFleetAndEsnRequest.getFleetName().equals(updateFleetT.getFleetName())){
			//校验车队名称是否存在
			int isExist = this.checkFleetName(cipFleetAndEsnRequest.getFleetName(),cipFleetAndEsnRequest.getType(),null != userT ? userT.getId() : null,cipFleetAndEsnRequest.getExternalUserId());
			if(isExist > 0){
				return BaseResponse.error(-98, "车队名称已存在！");
			}
		}
		String time = LocalTimeUtil.getRealCurrentTime();
		//1.根据车队主键id更新车队表
		CipFleetT cipFleetT = new CipFleetT();
		cipFleetT.setId(updateFleetT.getId());
		cipFleetT.setFleetName(cipFleetAndEsnRequest.getFleetName());
		cipFleetT.setFleetType(cipFleetAndEsnRequest.getFleetType());
		cipFleetT.setApplicationType(cipFleetAndEsnRequest.getApplicationType());
		if (1 != cipFleetAndEsnRequest.getType()) {
			cipFleetT.setExternalUserId(cipFleetAndEsnRequest.getExternalUserId());
			cipFleetT.setUserId(userChannelTMapper.getUserChannelByExternalUserIdAndChannel(cipFleetAndEsnRequest.getExternalUserId(),String.valueOf(type)));
			cipFleetT.setServiceChannel(String.valueOf(cipFleetAndEsnRequest.getType()));
			cipFleetT.setUpdator(Long.valueOf(cipFleetAndEsnRequest.getType()));
		} else {
			cipFleetT.setUserId(userT.getId());
			if (updateFleetT.getServiceChannel()==null) {
				cipFleetT.setServiceChannel("1");
			}
			cipFleetT.setUpdator(userT.getId());
		}
		cipFleetT.setUpdateTime(time);
		//修改车队同步cip
		cipFleetAndEsnRequest.setServiceChannel(cipFleetT.getServiceChannel());
		cipFleetAndEsnRequest.setType(cipFleetAndEsnRequest.getType());
		cipFleetAndEsnRequest.setExternalUserId(cipFleetT.getExternalUserId());
		cipFleetAndEsnRequest.setUserId(String.valueOf(cipFleetT.getUserId()));
		cipFleetAndEsnRequest.setCipFleetId(updateFleetT.getCipFleetId());
		cipFleetAndEsnRequest.setFleetCode(updateFleetT.getFleetCode());
		CipEntityResponse response = cipServiceApi.fleetUpdateCip(cipFleetAndEsnRequest);
		if(!(null != response && "0".equals(response.getStatus()))){
			String msg = null != response && StringUtils.isNotBlank(response.getMsg()) ? response.getMsg() : "同步cip失败";
			return BaseResponse.error(-99,msg);
		}
		int updateFleetNum = cipFleetMapper.updateFleet(cipFleetT);
		//2.删除车队之前的esn数据，重新维护车队和esn绑定关系
		if (1 != type) {
			cipFleetMapper.deleteVehicle(cipFleetT.getId(), Long.valueOf(type), time);
		} else {
			cipFleetMapper.deleteVehicle(cipFleetT.getId(), userT.getId(), time);
		}
		List<CipFleetAndEsnRequest.EsnRequest> esnList = cipFleetAndEsnRequest.getEsnList();
		if (updateFleetNum > 0 && CollectionUtils.isNotEmpty(esnList)) {
			esnList.stream().forEach(esn -> {
				CipVehicleT cipVehicleT = new CipVehicleT();
				if (1 != type) {
					cipVehicleT.setCreator(Long.valueOf(type));
					cipVehicleT.setExternalUserId(cipFleetAndEsnRequest.getExternalUserId());
					cipVehicleT.setUserId(userChannelTMapper.getUserChannelByExternalUserIdAndChannel(cipFleetAndEsnRequest.getExternalUserId(),String.valueOf(type)));
				} else {
					cipVehicleT.setCreator(userT.getId());
					cipVehicleT.setUserId(userT.getId());
				}
				cipVehicleT.setFleetId(cipFleetT.getId());
				cipVehicleT.setEsn(esn.getEsn());
				cipVehicleT.setPlateNumber(esn.getPlateNumber());
				cipVehicleT.setCreateTime(time);
				cipFleetMapper.insertVehicle(cipVehicleT);
				//3.更新发动机基础数据表里对应esn的应用类型和动力类型字段
				if (1 == type) {
					Map<String, Object> esnMap = new HashMap<>();
					esnMap.put("esnPowerType", cipFleetT.getFleetType());
					esnMap.put("esnApplicationType", cipFleetT.getApplicationType());
					esnMap.put("ESN", esn.getEsn());
					engineMsgDao.updateMsgByEsn(esnMap);
				}
			});
		}
		//陕康云  同步的车队至 medb 更新
		if(cipFleetAndEsnRequest.getType()==4 && null != updateFleetT.getExternalFleetId()){
			cipFleetT.setExternalFleetId(updateFleetT.getExternalFleetId());
			cipFleetT.setFleetName(cipFleetAndEsnRequest.getFleetName());
			Long userChannelByExternalUserIdAndChannel = userChannelTMapper.getUserChannelByExternalUserIdAndChannel(cipFleetAndEsnRequest.getExternalUserId(), String.valueOf(cipFleetAndEsnRequest.getType()));
			UserT userTSelect = userTDao.selectById(userChannelByExternalUserIdAndChannel);
			if (null != userTSelect) {
				if (StringUtils.isNotBlank(userTSelect.getShankangWWID())) {
					List<String> esnStrList = new ArrayList<>();
					if(CollectionUtils.isNotEmpty(esnList)) {
						esnStrList  = esnList.stream().map(esn -> esn.getEsn()).collect(Collectors.toList());
					}
					shanKangSycMedbFleetService.sycUpdateMedbFleet(cipFleetT,userTSelect,esnStrList);
				}
			}
		}
		return BaseResponse.success(updateFleetNum);
	}

	//批量修改车队接口(先删除后添加)
	@Override
	public void updateFleetByUserId(Long oldUserId, Long userId, String externalUserId, Integer type) {
		String time = LocalTimeUtil.getRealCurrentTime();
		List<CipFleetAndEsnRequest> esnRequestList = cipFleetMapper.getFleetsByUserId(oldUserId);
		for(CipFleetAndEsnRequest cipFleetAndEsnRequest : esnRequestList){

			//1.根据车队主键id更新车队表
			CipFleetT cipFleetT = new CipFleetT();
			cipFleetT.setId(cipFleetAndEsnRequest.getFleetId());
			cipFleetT.setFleetName(cipFleetAndEsnRequest.getFleetName());
			cipFleetT.setFleetType(cipFleetAndEsnRequest.getFleetType());
			cipFleetT.setApplicationType(cipFleetAndEsnRequest.getApplicationType());
			cipFleetT.setUserId(userId);
			cipFleetT.setExternalUserId(externalUserId);
			cipFleetT.setServiceChannel(String.valueOf(type));
			cipFleetT.setUpdator(userId);
			cipFleetT.setUpdateTime(time);
			List<Map<String, Object>> fleetEsnList = cipVehicleMapper.getFleetEsnList(cipFleetAndEsnRequest.getFleetId(), oldUserId,null, 1);
			List<CipFleetAndEsnRequest.EsnRequest>  esnList = JSON.parseArray(JSON.toJSONString(fleetEsnList), CipFleetAndEsnRequest.EsnRequest.class);
			cipFleetAndEsnRequest.setEsnList(esnList);
			cipFleetAndEsnRequest.setType(type);
			cipFleetAndEsnRequest.setServiceChannel(cipFleetT.getServiceChannel());
			cipFleetAndEsnRequest.setExternalUserId(cipFleetT.getExternalUserId());
			cipFleetAndEsnRequest.setUserId(String.valueOf(cipFleetT.getUserId()));
			cipFleetAndEsnRequest.setFleetCode(cipFleetAndEsnRequest.getFleetCode());
			int updateFleetNum = cipFleetMapper.updateFleet(cipFleetT);

			CipEntityResponse updateResponse = cipServiceApi.fleetUpdateCip(cipFleetAndEsnRequest);
			log.info("修改车队结果:" + updateResponse);

			//2.删除车队之前的esn数据，重新维护车队和esn绑定关系
			cipFleetMapper.deleteVehicle(cipFleetT.getId(), oldUserId, time);
			if (updateFleetNum > 0 && CollectionUtils.isNotEmpty(esnList)) {
				esnList.stream().forEach(esn -> {
					CipVehicleT cipVehicleT = new CipVehicleT();
					cipVehicleT.setCreator(userId);
					cipVehicleT.setUserId(userId);
					cipVehicleT.setExternalUserId(externalUserId);
					cipVehicleT.setFleetId(cipFleetT.getId());
					cipVehicleT.setEsn(esn.getEsn());
					cipVehicleT.setPlateNumber(esn.getPlateNumber());
					cipVehicleT.setCreateTime(time);
					cipFleetMapper.insertVehicle(cipVehicleT);
				});
			}

			//1.插入车队表
			CipFleetT addCipFleetT = new CipFleetT();
			addCipFleetT.setFleetName(cipFleetAndEsnRequest.getFleetName());
			addCipFleetT.setFleetType(cipFleetAndEsnRequest.getFleetType());
			addCipFleetT.setApplicationType(cipFleetAndEsnRequest.getApplicationType());
			addCipFleetT.setCreator(oldUserId);
			addCipFleetT.setUserId(oldUserId);
			addCipFleetT.setServiceChannel("1");
			addCipFleetT.setType(1);
			addCipFleetT.setCreateTime(time);
			addCipFleetT.setFleetCode("fl" + cipFleetMapper.getFleetCount());
			//添加车队同步cip
			cipFleetAndEsnRequest.setServiceChannel(addCipFleetT.getServiceChannel());
			cipFleetAndEsnRequest.setExternalUserId(addCipFleetT.getExternalUserId());
			cipFleetAndEsnRequest.setUserId(String.valueOf(addCipFleetT.getUserId()));
			cipFleetAndEsnRequest.setFleetCode(addCipFleetT.getFleetCode());
			CipSuccessResponse response = cipServiceApi.fleetAddCip(cipFleetAndEsnRequest);
			if(null != response && "0".equals(response.getStatus()) && null != response.getData() && StringUtils.isNotBlank(response.getData().getFleetId())) {
				addCipFleetT.setCipFleetId(response.getData().getFleetId());
				int insertFleetNum = cipFleetMapper.insertFleet(addCipFleetT);
				//2.车队和esn绑定关系
				List<CipFleetAndEsnRequest.EsnRequest> addEsnList = cipFleetAndEsnRequest.getEsnList();
				if (insertFleetNum > 0 && CollectionUtils.isNotEmpty(addEsnList)) {
					addEsnList.stream().forEach(esn -> {
						CipVehicleT cipVehicleT = new CipVehicleT();
						cipVehicleT.setCreator(oldUserId);
						cipVehicleT.setUserId(oldUserId);
						cipVehicleT.setFleetId(addCipFleetT.getId());
						cipVehicleT.setEsn(esn.getEsn());
						cipVehicleT.setPlateNumber(esn.getPlateNumber());
						cipVehicleT.setCreateTime(time);
						cipFleetMapper.insertVehicle(cipVehicleT);
					});
				}
			}
		}
	}

	@Override
	public void updateFleetList() {
		List<Long> userIdList = cipFleetMapper.appFleetUseridList();
		for(Long userId : userIdList){
			this.updateFleetListByUserId(userId);
		}
	}

	@Override
	public void updateFleetListByUserId(Long userId) {
		String time = LocalTimeUtil.getRealCurrentTime();
		List<CipFleetAndEsnRequest> esnRequestList = cipFleetMapper.getFleetsByUserId(userId);
		for(CipFleetAndEsnRequest cipFleetAndEsnRequest : esnRequestList){
			//删除车队同步cip
			CipFleetUpdateRequest delRequest = new CipFleetUpdateRequest();
			delRequest.setFleetId(cipFleetAndEsnRequest.getCipFleetId());
			delRequest.setChannel(cipFleetAndEsnRequest.getServiceChannel());
			CipEntityResponse response1 = cipServiceApi.fleetDel(delRequest);
			if(null != response1 && "0".equals(response1.getStatus())){
				List<Map<String, Object>> fleetEsnList = cipVehicleMapper.getFleetEsnList(cipFleetAndEsnRequest.getFleetId(), userId,null, 1);
				List<CipFleetAndEsnRequest.EsnRequest>  esnList = JSON.parseArray(JSON.toJSONString(fleetEsnList), CipFleetAndEsnRequest.EsnRequest.class);
				cipFleetAndEsnRequest.setEsnList(esnList);
				List<UserChannelT> channelList = userChannelTMapper.getUserChannelListByUserId(Long.valueOf(cipFleetAndEsnRequest.getUserId()));
				if(CollectionUtils.isNotEmpty(channelList)){
					cipFleetAndEsnRequest.setServiceChannel(channelList.get(0).getServiceChannel());
					cipFleetAndEsnRequest.setExternalUserId(channelList.get(0).getExternalUserId());
				} else {
					cipFleetAndEsnRequest.setServiceChannel("1");
				}
				CipSuccessResponse response2 = cipServiceApi.fleetAddCip(cipFleetAndEsnRequest);
				if(null != response2 && "0".equals(response2.getStatus()) && null != response2.getData() && StringUtils.isNotBlank(response2.getData().getFleetId())) {
					CipFleetT cipFleetT = new CipFleetT();
					cipFleetT.setServiceChannel(cipFleetAndEsnRequest.getServiceChannel());
					cipFleetT.setCipFleetId(response2.getData().getFleetId());
					cipFleetT.setExternalUserId(cipFleetAndEsnRequest.getExternalUserId());
					cipFleetT.setId(cipFleetAndEsnRequest.getFleetId());
					cipFleetT.setUpdator(userId);
					cipFleetT.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
					cipFleetMapper.updateFleet(cipFleetT);
					cipFleetMapper.deleteVehicle(cipFleetAndEsnRequest.getFleetId(), userId, time);
					if (CollectionUtils.isNotEmpty(esnList)) {
						esnList.stream().forEach(esn -> {
							CipVehicleT cipVehicleT = new CipVehicleT();
							cipVehicleT.setCreator(userId);
							cipVehicleT.setUserId(userId);
							cipVehicleT.setExternalUserId(cipFleetAndEsnRequest.getExternalUserId());
							cipVehicleT.setFleetId(cipFleetAndEsnRequest.getFleetId());
							cipVehicleT.setEsn(esn.getEsn());
							cipVehicleT.setPlateNumber(esn.getPlateNumber());
							cipVehicleT.setCreateTime(time);
							cipFleetMapper.insertVehicle(cipVehicleT);
						});
					}
				}
			}
		}
	}

	//app删除车队
	@Transactional
	@Override
	public BaseResponse appDeleteFleet(Long fleetId,String cipFleetId,Integer type){
		//获取当前用户
		UserT userT = UserThreadLocal.get();
		if (null == fleetId && StringUtils.isBlank(cipFleetId)) {
			return BaseResponse.error(17,"缺少必填参数！");
		}
		CipFleetT updateFleetT = cipFleetMapper.getFleetById(fleetId, cipFleetId);
		if(null == updateFleetT){
			return BaseResponse.error(17, "未查询到车队数据！");
		}
		String time = LocalTimeUtil.getRealCurrentTime();
		//删除车队同步cip
		CipEntityResponse response = cipServiceApi.fleetDeleteCip(updateFleetT.getCipFleetId(),updateFleetT.getServiceChannel(),updateFleetT.getUserId());
		if(!(null != response && "0".equals(response.getStatus()))){
			String msg = null != response && StringUtils.isNotBlank(response.getMsg()) ? response.getMsg() : "同步cip失败";
			return BaseResponse.error(-99,msg);
		}
		int resNum = cipFleetMapper.deleteFleetById(-1, null == userT ? -1 : userT.getId(), time, updateFleetT.getId());
		if(resNum > 0) {
			cipVehicleMapper.deleteCipVehicleByFleetId(-1, null == userT ? -1 : userT.getId(), time, updateFleetT.getId());
		}
		//陕康云  同步的车队至 medb 更新
		if(type==4 && StringUtils.isNotBlank(updateFleetT.getExternalUserId()) && null != updateFleetT.getExternalFleetId()){
			Long userChannelByExternalUserIdAndChannel = userChannelTMapper.getUserChannelByExternalUserIdAndChannel(updateFleetT.getExternalUserId(), String.valueOf(type));
			UserT userTSelect = userTDao.selectById(userChannelByExternalUserIdAndChannel);
			if (null != userTSelect) {
				if (StringUtils.isNotBlank(userTSelect.getShankangWWID())) {
					shanKangSycMedbFleetService.sycdeleteMedbFleet(updateFleetT.getExternalFleetId(),userTSelect.getShankangWWID());
				}
			}
		}
		return BaseResponse.success(resNum);
	}

	@Override
	public void appDeleteFleetByUserId(Long userId) {
		String time = LocalTimeUtil.getRealCurrentTime();
		List<CipFleetAndEsnRequest> esnRequestList = cipFleetMapper.getFleetsByUserId(userId);
		for(CipFleetAndEsnRequest updateFleetT : esnRequestList){
			//删除车队同步cip
			CipEntityResponse response = cipServiceApi.fleetDeleteCip(updateFleetT.getCipFleetId(),updateFleetT.getServiceChannel(),Long.valueOf(updateFleetT.getUserId()));
			if(null != response && "0".equals(response.getStatus())){
				//app删除车队
				cipFleetMapper.deleteFleetById(-1, userId, time, updateFleetT.getFleetId());
			}
		}
	}
	@Override
	public void appDeleteFleetByUserIdAndChannel(Long userId,String serviceChannel) {
		String time = LocalTimeUtil.getRealCurrentTime();
		List<CipFleetAndEsnRequest> esnRequestList = cipFleetMapper.getFleetsByUserId(userId);
		for(CipFleetAndEsnRequest updateFleetT : esnRequestList){
			if (StringUtils.isNotBlank(updateFleetT.getServiceChannel()) && updateFleetT.getServiceChannel().equals(serviceChannel)) {
				//删除车队同步cip
				CipEntityResponse response = cipServiceApi.fleetDeleteCip(updateFleetT.getCipFleetId(),updateFleetT.getServiceChannel(),Long.valueOf(updateFleetT.getUserId()));
				if(null != response && "0".equals(response.getStatus())){
					//app删除车队
					cipFleetMapper.deleteFleetById(-1, userId, time, updateFleetT.getFleetId());
				}
			}
		}
	}

	@Override
	public BaseResponse appFleetHistory() {
		List<CipFleetAndEsnRequest> fleetList = cipFleetMapper.appFleetHistory();
		for(CipFleetAndEsnRequest request : fleetList){
			List<CipFleetAndEsnRequest.EsnRequest> esnList = new ArrayList<>();
			List<CipVehicleResponse> vehicleList = cipFleetMapper.getVehicleListByFleetId(request.getFleetId());
			for(CipVehicleResponse esn : vehicleList){
				CipFleetAndEsnRequest.EsnRequest esnRequest = new CipFleetAndEsnRequest.EsnRequest();
				esnRequest.setEsn(esn.getEsn());
				esnRequest.setPlateNumber(esn.getPlateNumber());
				esnList.add(esnRequest);
			}
			request.setEsnList(esnList);
			CipSuccessResponse response = cipServiceApi.fleetAddCip(request);
			if(null != response && "0".equals(response.getStatus()) && null != response.getData() && StringUtils.isNotBlank(response.getData().getFleetId())){
                cipFleetMapper.updateCIPFleetIdById(response.getData().getFleetId(),request.getFleetId());
			}
		}
		return BaseResponse.success();
	}
}
